import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ListViewPage extends StatelessWidget {
  const ListViewPage({super.key});

  ListView generateListView1() {
    return ListView(
      padding: const EdgeInsets.only(left: 10, right: 10),
      children: <Widget>[
        Container(
          height: 50,
          color: Colors.red[600],
          child: const Center(
            child: Text("Entry A"),
          ),
        ),
        Container(
          height: 50,
          color: Colors.red[500],
          child: const Center(
            child: Text("Entry B"),
          ),
        ),
        Container(
          height: 50,
          color: Colors.red[100],
          child: const Center(
            child: Text("Entry C"),
          ),
        )
      ],
    );
  }

  generateListView2() {
    List<String> entries = <String>['A', 'B', 'C'];
    List<int> colorCodes = <int>[600, 500, 100];
    return ListView.builder(
        padding: const EdgeInsets.only(left: 10, right: 10),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            height: 40,
            color: Colors.blue[colorCodes[index]],
            child: Center(
              child: Text('Entry ${entries[index]}'),
            ),
          );
        });
  }

  generateListView3() {
    List<String> entries = <String>['A', 'B', 'C'];
    List<int> colorCodes = <int>[600, 500, 100];
    return ListView.separated(
      itemCount: entries.length,
      itemBuilder: (BuildContext context, int index) => Container(
        height: 50,
        color: Colors.amber[colorCodes[index]],
        child: Center(
          child: Text('Entry ${entries[index]}'),
        ),
      ),
      separatorBuilder: (BuildContext context, int index) => const Divider(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("ListViewPage"),
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          alignment: Alignment.center,
          color: Colors.lightGreen,
          child: Container(
            alignment: Alignment.center,
            color: Colors.blueGrey,
            child: Column(
              // mainAxisSize: MainAxisSize.min,
              // crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text(
                  "ListView-children",
                  style: TextStyle(
                    backgroundColor: Colors.red,
                  ),
                ),
                // Spacer(),
                const SizedBox(
                  height: 2,
                ),
                SizedBox(
                  width: 120,
                  height: 100,
                  child: generateListView1(),
                ),
                const SizedBox(
                  height: 20,
                ),
                const Text(
                  "ListView.builder",
                  style: TextStyle(backgroundColor: Colors.blue),
                ),
                SizedBox(
                  width: 120,
                  height: 100,
                  child: generateListView2(),
                ),
                const SizedBox(
                  height: 20,
                ),
                const Text(
                  "ListView.separated",
                  style: TextStyle(
                    backgroundColor: Colors.amber,
                  ),
                ),
                SizedBox(width: 120, height: 100, child: generateListView3()),
                ElevatedButton(
                    onPressed: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ListTileSelectExample()));
                    },
                    style: ButtonStyle(),
                    child: const Text(
                      "listview列表项选择功能",
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ))
              ],
            ),
          ),
        ));
  }
}

//=======================选择列表页面=======================
//=======================选择列表页面=======================
//=======================选择列表页面=======================

class ListTileSelectExample extends StatefulWidget {
  const ListTileSelectExample({super.key});

  @override
  State<StatefulWidget> createState() {
    return ListTileSelectExampleState();
  }
}

class ListTileSelectExampleState extends State<ListTileSelectExample> {
  bool isSelectionMode = false; //选择模式
  int listLength = 30;
  late List<bool> _selected;
  bool _selectAll = false;
  bool _isGridMode = false;

  void _initSelection() {
    _selected = List<bool>.generate(listLength, (index) => false);
  }

  @override
  void initState() {
    super.initState();
    _initSelection();
  }

  @override
  void dispose() {
    _selected.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ListTitle section'),
        leading: isSelectionMode
            ? IconButton(
                onPressed: () {
                  setState(() {
                    isSelectionMode = false;
                  });
                  _initSelection();
                },
                icon: const Icon(Icons.close))
            : const SizedBox(),
        actions: [getDisplayModeWidget(), getSelectAllWidget()],
      ),
      body: _isGridMode
          ? GridBuilder(
              isSelectionMode: isSelectionMode,
              onSelectionChange: (bool x) {
                setState(() {
                  isSelectionMode = x;
                });
              },
              selectedList: _selected,
            )
          : ListBuilder(
              isSelectionMode: isSelectionMode,
              selectedList: _selected,
              onSelectionChanged: (bool x) {
                setState(() {
                  isSelectionMode = x;
                });
              },
            ),
    );
  }

  Widget getDisplayModeWidget() {
    if (_isGridMode) {
      return IconButton(
          onPressed: () {
            setState(() {
              _isGridMode = false;
            });
          },
          icon: const Icon(Icons.list));
    } else {
      return IconButton(
          onPressed: () {
            setState(() {
              _isGridMode = true;
            });
          },
          icon: const Icon(Icons.grid_on));
    }
  }

  Widget getSelectAllWidget() {
    if (isSelectionMode) {
      return TextButton(
          onPressed: () {
            _selectAll = !_selectAll;
            setState(() {
              _selected =
                  List<bool>.generate(listLength, (index) => _selectAll);
            });
          },
          child: !_selectAll
              ? const Text(
                  "select all",
                  style: TextStyle(color: Colors.white),
                )
              : const Text(
                  "unselect all",
                  style: TextStyle(color: Colors.white),
                ));
    } else {
      return Container();
    }
  }
}

class GridBuilder extends StatefulWidget {
  final bool isSelectionMode; //选择模式
  final Function(bool)? onSelectionChange;
  final List<bool> selectedList;

  const GridBuilder(
      {super.key,
      required this.isSelectionMode,
      this.onSelectionChange,
      required this.selectedList});

  @override
  State<StatefulWidget> createState() => GridBuilderState();
}

class GridBuilderState extends State<GridBuilder> {
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        itemCount: widget.selectedList.length,
        gridDelegate:
            const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemBuilder: (_, index) {
          return InkWell(
            onTap: () => _toggle(index),
            onLongPress: () {
              if (!widget.isSelectionMode) {
                setState(() {
                  widget.selectedList[index] = true;
                });
                widget.onSelectionChange!(true);
              }
            },
            child: GridTile(
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('item $index'),
                    widget.isSelectionMode
                        ? Checkbox(
                            value: widget.selectedList[index],
                            onChanged: (bool? x) {
                              _toggle(index);
                            })
                        : const Icon(Icons.image)
                  ],
                ),
              ),
            ),
          );
        });
  }

  void _toggle(index) {
    if (widget.isSelectionMode) {
      setState(() {
        widget.selectedList[index] = !widget.selectedList[index];
      });
    }
  }
}

class ListBuilder extends StatefulWidget {
  final bool isSelectionMode;
  final List<bool> selectedList;
  final Function(bool)? onSelectionChanged;

  const ListBuilder(
      {super.key,
      required this.isSelectionMode,
      required this.selectedList,
      required this.onSelectionChanged});

  @override
  State<StatefulWidget> createState() {
    return ListBuilderState();
  }
}

class ListBuilderState extends State<ListBuilder> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: widget.selectedList.length,
        itemBuilder: (context, index) {
          return ListTile(
            onTap: () => _toggle(index),
            onLongPress: () {
              if (!widget.isSelectionMode) {
                setState(() {
                  widget.selectedList[index] = true;
                });
                widget.onSelectionChanged!(true);
              }
            },
            trailing: widget.isSelectionMode
                ? Checkbox(
                    value: widget.selectedList[index],
                    onChanged: (bool? x) => _toggle(index))
                : const SizedBox.shrink(),
            title: Text('item $index'),
          );
        });
  }

  void _toggle(int index) {
    if (widget.isSelectionMode) {
      setState(() {
        widget.selectedList[index] = !widget.selectedList[index];
      });
    }
  }
}
